package processor;

import model.CrawlerLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Selectable;
//import util.LogToKafka;
//import util.LogToMysql;
import util.MyString;
import util.Mytime;

import java.util.List;

//import static processor.LoginProcessor.isRedirectedToLoginPage;
//import static processor.LoginProcessor.logger;

public class SearchPageProcessor {

    private static final String HOST = "https://www.qichacha.com";
    private static final String BASE ="#base";
    private static Logger logger = LoggerFactory.getLogger(SearchPageProcessor.class);

    public static String processSearchPage(Page page){
        /**
         * @Description 根据搜索词进行页面对比，匹配对象为公司名称，曾用名，股票，产品等。
         * @param page
         * @return 定位到的公司Url
         */
        // 检验xpath路径是否为空
        List<Selectable> l = page.getHtml().xpath("//tbody[@id=\"search-result\"]//td[3]").nodes();
//        LogToKafka logToKafka = new LogToKafka();
        String logStatus = "-";
        String logCompanyUnique = "-";
        //返回的搜索结果列表长度为0
        if (page.getHtml().xpath("//tbody[@id=\"search-result\"]//td[3]").nodes().size() == 0){
            // 是否为登陆失效问题
//            if (isRedirectedToLoginPage(page)){
//                logStatus = "LogOut";
//            }
            // 是否确实没有搜索结果
//            else {
//                logStatus = "NotFound";
//            }
            logger.warn("未查找到任何结果:"+page.getRequest().getExtra("search_word").toString());
        }
        // 返回的搜索结果长度大于0
        else {
            // 迭代查找搜索词是否与正式名称匹配
            for (Selectable node:page.getHtml().xpath("//tbody[@id=\"search-result\"]//td[3]").nodes()){
                if (MyString.isEqual(node.xpath("//a[@class=\"ma_h1\"]/allText()").toString(),page.getRequest().getExtra("search_word").toString())){
                    page.putField("company_name",node.xpath("//a[@class=\"ma_h1\"]/allText()").toString().trim());
                    page.putField("unique",node.xpath("//a[@class=\"ma_h1\"]/@href").toString().trim());
                    page.putField("search_word",page.getRequest().getExtra("search_word").toString());
                    page.putField("search_word_matched_type","现用名");
                    logger.info("查找到公司:"+page.getResultItems().get("company_name"));
                    logger.info("企查查地址:"+page.getResultItems().get("unique"));
                    logStatus = "Found";
                    logCompanyUnique = page.getResultItems().get("unique").toString().replace("/firm_","").replace(".html","");
                    break;
                }
                //查找搜索词是否与曾用名匹配
                String[] strings = node.xpath("//p[4]/allText()").toString().split("：");
                if(strings.length>1 && strings[0].contains("曾用名") && MyString.isEqual(strings[1],page.getRequest().getExtra("search_word").toString())){
                    page.putField("search_word_matched_type",strings[0]);
                    page.putField("company_name",node.xpath("//a[@class=\"ma_h1\"]/allText()").toString());
                    page.putField("search_word",page.getRequest().getExtra("search_word").toString());
                    page.putField("unique",node.xpath("//a[@class=\"ma_h1\"]/@href").toString().trim());
                    logger.info("查找到公司:"+page.getResultItems().get("search_word")+" 曾用名为:"+page.getResultItems().get("search_word")+" 现用名为:"+page.getResultItems().get("company_name"));
                    logger.info("企查查地址:"+page.getResultItems().get("unique"));
                    logStatus = "Found";
                    logCompanyUnique = page.getResultItems().get("unique").toString().replace("/firm_","").replace(".html","");
                    break;
                }
                //查找搜索词是否与其他参数匹配如股票简称，产品/品牌等
                else if (strings.length>1){
                    page.putField("search_word_matched_type",strings[0]);
                    page.putField("company_name",node.xpath("//a[@class=\"ma_h1\"]/allText()").toString());
                    page.putField("search_word",page.getRequest().getExtra("search_word").toString());
                    page.putField("unique",node.xpath("//a[@class=\"ma_h1\"]/@href").toString().trim());
                    logger.info("查找关键词:"+page.getResultItems().get("search_word")+" 搜索结果: ");
                    logger.info(page.getResultItems().get("search_word_matched_type")+"为 "+strings[1]+" 公司名称为 "+ page.getResultItems().get("company_name")+" 企查查地址:"+page.getResultItems().get("unique"));
                    logStatus = "Found";
                    logCompanyUnique = page.getResultItems().get("unique").toString().replace("/firm_","").replace(".html","");
                    break;
                }
                else {
                    logStatus = "NotFound";
                    logger.warn("未匹配到搜索词:"+page.getRequest().getExtra("search_word").toString());
                }
                // 选择第一个结果
//                else {
//                    page.putField("company_name",node.xpath("//a[@class=\"ma_h1\"]/allText()").toString().trim());
//                    page.putField("unique",node.xpath("//a[@class=\"ma_h1\"]/@href").toString().trim());
//                    page.putField("search_word",page.getRequest().getExtra("search_word").toString());
//                    page.putField("search_word_matched_type","第一个匹配到");
//                    System.out.println("查找到搜索推荐第一家公司:"+page.getResultItems().get("company_name"));
//                    System.out.println("企查查地址:"+page.getResultItems().get("unique"));
//                    break;
//                }

            }
        }
        // 记录日志
//        logToKafka.log(new CrawlerLog(page.getRequest().getExtra("job_id").toString(),
//                page.getRequest().getExtra("search_word").toString(),
//                logStatus,
//                logCompanyUnique,
//                Mytime.getTime()));
        if (page.getResultItems().get("unique") != null){
            //将firm_xx.html#base返回,不直接传.html是防止出现ipo类公司会跳转到.html#ipo
            return HOST+page.getResultItems().get("unique")+BASE;
        }else{
            return "";
        }

    }
}
